<template>
  <div class="base-container" id="main">
    <t-loading text="加载中..." :fullscreen="false" attach="#main" :loading="applyLoading" size="medium">
    </t-loading>
    <!-- 基本信息 -->
    <t-form ref="form"   class="step-form table-form" :data="formData"
            :rules="rules"
            labelWidth="180px">
      <t-row>
        <t-col :span="2" class="title">科技示范工程名称</t-col>
        <t-col :span="10">{{ implementPlanData.projectName }}</t-col>
      </t-row>
      <t-row>
        <t-col :span="2" class="title">负责人</t-col>
        <t-col :span="10">{{ projectData.projectLeader.name }}</t-col>
      </t-row>
      <t-row>
        <t-col :span="2" class="title">第一承担单位</t-col>
        <t-col :span="10">{{ projectData.declareDeptName }}</t-col>
      </t-row>
      <t-row>
        <t-col :span="2" class="title">合作单位</t-col>
        <t-col :span="10">{{ companyList.join(',') }}</t-col>
      </t-row>
      <t-row>
        <t-col :span="2" class="title">实施起止年月</t-col>
        <t-col :span="10">{{ implementPlanData.startDate.substring(0, 4) }} 年 {{ implementPlanData.startDate.substring(5, 7) }} 月 至
          {{ implementPlanData.endDate.substring(0, 4) }} 年 {{ implementPlanData.endDate.substring(5, 7) }} 月
        </t-col>
      </t-row>
      <t-row>
        <t-col :span="2" class="title"><span class="require">*</span>申请验收时间</t-col>
        <t-col :span="4">
          <t-form-item name="preAcceptanceDate">
            <t-date-picker clearable v-model="formData.preAcceptanceDate">

            </t-date-picker>
          </t-form-item>
        </t-col>
        <t-col :span="6" style="display: flex;flex-direction: column;border: 0;padding: 0px !important">
          <t-row style="width: 100%;">
            <t-col :span="2" class="title"><span class="require">*</span>联系人</t-col>
            <t-col :span="10">
              <t-form-item name="linker">
                <t-input clearable v-model="formData.linker"></t-input>
              </t-form-item>
            </t-col>
          </t-row>
          <t-row style="width: 100%;">
            <t-col :span="2" class="title"><span class="require">*</span>联系电话</t-col>
            <t-col :span="10">
              <t-form-item name="linkerPhone">
                <t-input clearable placeholder="请输入手机号" v-model="formData.linkerPhone"></t-input>
              </t-form-item>
            </t-col>
          </t-row>
        </t-col>
      </t-row>
      <t-row style="min-height: 300px">
        <t-col :span="2" class="title"><span class="require">*</span>提供验收的技术文件清单</t-col>
        <t-col :span="10" style="justify-content: center">
          <t-table size="small" row-key="id" :columns="projectFileColumns" :data="projectFileData">
            <template #id="{row, rowIndex}">
              {{ rowIndex+1 }}
            </template>
            <template #op="{row}">
              <file-upload tips="限制pdf" accept="application/pdf" v-model="row.fileIds" :moduleKey="row.moduleKey"
                           :fileList="row.fileLists"
                           :multiple="true">
                <t-button variant="outline">
                  <t-icon name="cloud-upload" slot="icon"/>
                  点击上传
                </t-button>
              </file-upload>
            </template>
            <template #c1="{row}">
              <a v-if="row.c3" class="t-button-link" :href="`${file_domain}/${row.c3}`" target="_blank">{{ row.c1 }}</a>
              <div v-else>{{ row.c1 }}</div>
            </template>
          </t-table>
        </t-col>
      </t-row>
    </t-form>
    <t-row style="text-align: center;margin-top: 20px">
      <t-col :span="12">
        <t-space :size="10">
          <t-button theme="primary" :loading="applyLoading" @click="onSubmit(1)">{{
              applyLoading ? '提交中...' : '暂存'
            }}
          </t-button>
          <t-button theme="primary" :loading="applyLoading" @click="onSubmit(2)">{{
              applyLoading ? '提交中...' : '提交'
            }}
          </t-button>
        </t-space>
      </t-col>
    </t-row>
  </div>
</template>

<script>
import { VITE_FILE_DOMAIN } from '@/api/upload'
import FileUpload from "@/components/FileUpload/index.vue"
import {getFiles} from "@/api/common";

export default {
  name: "acceptance_apply",
  dicts: ["apply_type"],
  components: {
    FileUpload
  },
  data() {
    return {
      site_tag: import.meta.env.VITE_SITE_TAG,
      file_domain: VITE_FILE_DOMAIN,
      projectFileData: [
        {
          id: 1,
          c1: "科技示范工程依托工程(项目)已通过验收或总结评价等",
          c2: "是",
          moduleKey: "preProjectYSZJPJ",
          fileIds: [],
          fileLists: [],
          require: true,
        },
        {
          id: 2,
          c1: "科技示范工程实施方案中明确的实施内容和预期目标已全部完成",
          c2: "是",
          moduleKey: "preProjectYSSSNJYQMB",
          fileIds: [],
          fileLists: [],
          require: true,
        },
        {
          id: 7,
          c1: "预验收专家评审相关附件",
          c2: "是",
          moduleKey: "preProjectZJSP",
          fileIds: [],
          fileLists: [],
          require: true,
        },
        {
          id: 3,
          c1: "依托科技示范工程实施的省厅科技项目已通过验收",
          c2: "否",
          moduleKey: "preProjectYSYTGSS",
          fileIds: [],
          fileLists: [],
          require: false,
        },
        {
          id: 4,
          c1: "验收意见",
          c2: "否",
          moduleKey: "preProjectYSYJ",
          fileIds: [],
          fileLists: [],
          require: false,
        },
        {
          id: 5,
          c1: "相关成果证明",
          c2: "否",
          moduleKey: "preProjectYSCGZM",
          fileIds: [],
          fileLists: [],
          require: false,
        },
        {
          id: 6,
          c1: "其他",
          c2: "否",
          moduleKey: "preProjectYSQT",
          fileIds: [],
          fileLists: [],
          require: false,
        },
      ],
      projectFileColumns: [
        {
          colKey: "id",
          title: "序号",
          align: "center",
          width: 64
        },
        {
          colKey: "c1",
          title: "附件名称",
          align: "center",
        },

        {
          colKey: "c2",
          title: "是否必需",
          align: "center",
        },
        {
          colKey: "op",
          title: "操作",
          align: "left",
        },
      ],
      applyLoading: false,
      formData: {
        id: null,
        linker: '',
        linkerPhone: '',
        preAcceptanceDate: '',
      },
      companyList: [],
      rules: {
        linker: [
          {
            required: true,
            message: "联系人不能为空",
          }
        ],
        linkerPhone: [
          {
            required: true,
            message: "联系电话不能为空",
          },
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: "联系电话请输入正确的手机号码",
          },
        ],
        preAcceptanceDate: [
          {
            required: true,
            message: "申请验收时间不能为空",
          }
        ],
        'sysAttMainVo.sysAttMainIds': [
          {required: true, validator: (val) => val.length > 0, message: "提供验收的技术文件清单不能为空", type: "error"}
        ],
      },
      projectId: null,
      projectData: {
        projectLeader: {
          name: ''
        }
      },
      taskId: null,
      implementPlanData: {
        startDate: '',
        endDate: '',
        projectCompanyList: []
      }
    }
  },
  async created() {
    const projectId = this.$route.params && this.$route.params.taskId;
    if (!projectId) {
      this.$message.error("缺少项目id");
      return false;
    }
    this.projectId = projectId;
    this.taskId = projectId;
    this.applyLoading = true;
    await this.$api.kjsf.project.get(Number(this.projectId)).then(pro => {
      this.projectData = pro.data;
    }).catch((e) => {
      this.$message.error(e.toString());
    });
    await this.$api.kjsf.implement.projectEmbodimentGetByProjectId(this.projectId).then(response => {
      if (response.data) {
        Object.assign(this.implementPlanData, response.data)
        this.companyList = this.implementPlanData.projectCompanyList.filter(val => val.type === '2').map(val => val.name)
      }
      this.applyLoading = false;
    }).catch((e) => {
      this.applyLoading = false;
      this.$message.error(e.toString());
    });
    getFiles(this.projectId).then((res) => {
      const files = {}
      res.data.forEach((item) => {
        if (!files[item.moduleKey]) {
          files[item.moduleKey] = []
        }
        files[item.moduleKey].push({
          name: item.fileName,
          url: item.fullFilePath,
          id: item.id,
          filePath: item.filePath
        })
      })
      this.projectFileData.forEach((val, index) => {
        this.projectFileData[index].fileLists = files[val.moduleKey] || [];
        this.projectFileData[index].fileIds = files[val.moduleKey]?.map(val => val.id) || [];
      })
    });
    this.$api.kjsf.acceptance.preGetByProject(this.projectId).then(response => {
      if (response.data) {
        Object.assign(this.formData, response.data)
      }
      this.applyLoading = false;
    }).catch((e) => {
      this.applyLoading = false;
      this.$message.error(e.toString());
    });
  },
  methods: {
    onSubmit(type) {
      const sysAttMainIds = []
      this.projectFileData.forEach(val => {
        sysAttMainIds.push(...val.fileIds)
      })
      if (type === 1) {
        this.applyLoading = true;
        this.$api.kjsf.project.update({
          id: this.projectId,
          sysAttMainVo: {
            sysAttMainIds
          }
        }).then(response => {
          if (!this.formData.id) {
            this.$api.kjsf.acceptance.preAdd({
              ...this.formData,
              projectId: this.projectId,
            }).then(response => {
              this.formData.id = response.data.id;
              this.$message.success("暂存成功");
              this.applyLoading = false;
            }).catch((e) => {
              this.applyLoading = false;
              this.$message.error(e.toString());
            });
          } else {
            this.$api.kjsf.acceptance.preUpdate({
              ...this.formData,
              projectId: this.projectId,
            }).then(response => {
              this.$message.success("暂存成功");
              this.applyLoading = false;
            }).catch((e) => {
              this.applyLoading = false;
              this.$message.error(e.toString());
            });
          }
        }).catch((e) => {
          this.applyLoading = false;
          this.$message.error(e.toString());
        });


      } else {
        this.$refs.form.validate().then((validateResult) => {
          if (validateResult === true) {
            const isValidate = this.projectFileData.every(val => {
              if (val.require && val.fileIds.length <= 0) {
                this.$message.error(`提供验收的技术文件清单：需要上传${val.c1}`);
                return false;
              }
              return true
            })
            if (!isValidate) {
              return false
            }
            this.applyLoading = true;
            this.$api.kjsf.project.update({
              id: this.projectId,
              sysAttMainVo: {
                sysAttMainIds
              }
            }).then(response => {
              if (!this.formData.id) {
                this.$api.kjsf.acceptance.preAdd({
                  ...this.formData,
                  projectId: this.projectId,
                }).then(response => {
                  this.$api.kjsf.acceptance.preSubmit({
                    projectId: this.projectId,
                  }).then(response => {
                    this.$message.success("提交成功");
                    this.applyLoading = false;
                    this.close()
                  }).catch((e) => {
                    this.$message.error(e.toString());
                  });
                }).catch((e) => {
                  this.applyLoading = false;
                  this.$message.error(e.toString());
                });
              } else {
                this.$api.kjsf.acceptance.preSubmit({
                  ...this.formData,
                  projectId: this.projectId,
                  id: this.formData.id,
                }).then(response => {
                  this.$message.success("提交成功");
                  this.applyLoading = false;
                  this.close()
                }).catch((e) => {
                  this.applyLoading = false;
                  this.$message.error(e.toString());
                });
              }
            }).catch((e) => {
              this.applyLoading = false;
              this.$message.error(e.toString());
            });
          } else {
            const firstError = Object.values(validateResult)[0]?.[0]?.message;
            this.$message.error(firstError);
          }
        })

      }
    },
    close() {
      this.applyLoading = false;
      this.$tab.closeOpenPage({path: "/kjsf/acceptance/pre-project-my"})
    }
  }
}
</script>

<style scoped lang="less">
.span-title {
  font-weight: bold;
}

.span-sub-txt {
  margin-left: 20px;
}

.step-form {
  padding: 0 24px;
}

.t-row {
  margin-bottom: 14px;
}

.step-card {
  height: 100%;
  margin-bottom: 14px;
}
</style>
